<template>
    <el-dialog v-model="visible" title="设置不明水分摊规则" width="800px">
        <el-form :model="form" label-width="120px">
            <el-form-item label="分摊方式">
                <el-radio-group v-model="form.method">
                    <el-radio value="water" label="water">用水量比例</el-radio>
                    <el-radio value="area" label="area">面积比例</el-radio>
                    <el-radio value="person" label="person">人数比例</el-radio>
                    <el-radio value="custom" label="custom">自定义比例</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="添加用能户">
                <el-select v-model="selectedUser" filterable clearable placeholder="请选择用能户" @change="handleUserSelect">
                    <el-option v-for="user in availableUsers" :key="user.id" :label="user.name" :value="user.id" />
                </el-select>
            </el-form-item>

            <div v-if="form.users.length > 0" class="users-list">
                <div v-for="(user, index) in form.users" :key="user.id" class="user-item">
                    <div class="user-info">
                        <span class="user-name">{{ user.name }}</span>

                        <!-- 面积分摊 -->
                        <template v-if="form.method === 'area'">
                            <el-input-number v-model="user.area" :min="0" :precision="2" placeholder="面积(m²)"
                                @change="calculateRatios" />
                            <span class="ratio">{{ user.ratio.toFixed(2) }}%</span>
                        </template>

                        <!-- 用水量分摊 -->
                        <template v-if="form.method === 'water'">
                            <el-input-number v-model="user.water" :min="0" :precision="2" placeholder="用水量(m³)"
                                @change="calculateRatios" />
                            <span class="ratio">{{ user.ratio.toFixed(2) }}%</span>
                        </template>

                        <!-- 人数分摊 -->
                        <template v-if="form.method === 'person'">
                            <el-input-number v-model="user.persons" :min="0" :precision="0" placeholder="人数"
                                @change="calculateRatios" />
                            <span class="ratio">{{ user.ratio.toFixed(2) }}%</span>
                        </template>

                        <!-- 自定义比例 -->
                        <template v-if="form.method === 'custom'">
                            <el-input-number v-model="user.ratio" :min="0" :max="100" :precision="2" placeholder="比例(%)"
                                @change="adjustOtherRatios(index)" />
                        </template>

                        <el-button type="danger" circle size="small" @click="removeUser(index)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                        </el-button>
                    </div>
                </div>

                <div class="total-info">
                    <span>总计:</span>
                    <template v-if="form.method === 'area'">
                        <span>面积: {{ totalArea }}m² / </span>
                    </template>
                    <template v-if="form.method === 'water'">
                        <span>用水量: {{ totalWater }}m³ / </span>
                    </template>
                    <template v-if="form.method === 'person'">
                        <span>人数: {{ totalPersons }}人 / </span>
                    </template>
                    <span>比例: {{ totalRatio.toFixed(2) }}%</span>
                    <template v-if="form.method === 'custom' && Math.abs(totalRatio - 100) > 0.01">
                        <span class="error-text"> (请调整至100%)</span>
                    </template>
                </div>
            </div>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" :disabled="!isValid" @click="handleConfirm">
                    确认
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue';
import { Delete } from '@element-plus/icons-vue';
import { useEnergyUsersStore } from '@/stores/energyUser';

const props = defineProps({
    modelValue: Boolean,
    currentMethod: {
        type: String,
        default: 'water'
    }
});

const emit = defineEmits(['update:modelValue', 'confirm']);

const energyUsersStore = useEnergyUsersStore();
const visible = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
});

const form = ref({
    method: props.currentMethod,
    users: []
});

const selectedUser = ref(null);

const availableUsers = computed(() => {
    const selectedIds = form.value.users.map(u => u.id);
    return energyUsersStore.energyUserList.filter(u => !selectedIds.includes(u.id));
});

// 计算总量
const totalArea = computed(() =>
    form.value.users.reduce((sum, user) => sum + (user.area || 0), 0)
);

const totalWater = computed(() =>
    form.value.users.reduce((sum, user) => sum + (user.water || 0), 0)
);

const totalPersons = computed(() =>
    form.value.users.reduce((sum, user) => sum + (user.persons || 0), 0)
);

const totalRatio = computed(() =>
    form.value.users.reduce((sum, user) => sum + (user.ratio || 0), 0)
);

const isValid = computed(() => {
    if (form.value.users.length === 0) return false;

    switch (form.value.method) {
        case 'area':
            return form.value.users.every(user => user.area > 0);
        case 'water':
            return form.value.users.every(user => user.water > 0);
        case 'person':
            return form.value.users.every(user => user.persons > 0);
        case 'custom':
            return Math.abs(totalRatio.value - 100) < 0.01;
        default:
            return false;
    }
});

function handleUserSelect(userId) {
    if (!userId) return;

    const user = energyUsersStore.energyUserList.find(u => u.id === userId);
    if (user) {
        form.value.users.push({
            id: user.id,
            name: user.name,
            area: 0,
            water: 0,
            persons: 0,
            ratio: 0
        });
    }
    selectedUser.value = null;
}

function calculateRatios() {
    const users = form.value.users;
    if (users.length === 0) return;

    switch (form.value.method) {
        case 'area':
            if (totalArea.value > 0) {
                users.forEach(user => {
                    user.ratio = (user.area / totalArea.value) * 100;
                });
            }
            break;
        case 'water':
            if (totalWater.value > 0) {
                users.forEach(user => {
                    user.ratio = (user.water / totalWater.value) * 100;
                });
            }
            break;
        case 'person':
            if (totalPersons.value > 0) {
                users.forEach(user => {
                    user.ratio = (user.persons / totalPersons.value) * 100;
                });
            }
            break;
    }
}

function adjustOtherRatios(changedIndex) {
    if (form.value.method !== 'custom') return;

    const users = form.value.users;
    const totalOthers = users.reduce((sum, user, idx) =>
        idx !== changedIndex ? sum + (user.ratio || 0) : sum, 0
    );

    if (totalOthers + users[changedIndex].ratio > 100) {
        users[changedIndex].ratio = 100 - totalOthers;
    }
}

function removeUser(index) {
    form.value.users.splice(index, 1);
    if (form.value.method !== 'custom') {
        calculateRatios();
    }
}

function handleConfirm() {
    emit('confirm', {
        method: form.value.method,
        users: form.value.users.map(user => ({
            id: user.id,
            name: user.name,
            ratio: user.ratio
        }))
    });
    visible.value = false;
}

function handleCancel() {
    form.value.users = [];
    visible.value = false;
}
</script>

<style scoped>
.users-list {
    margin-top: 16px;
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 4px;
    padding: 16px;
}

.user-item {
    margin-bottom: 12px;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 12px;
}

.user-name {
    min-width: 120px;
}

.ratio {
    color: var(--el-text-color-secondary);
    min-width: 80px;
}

.total-info {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid var(--el-border-color-lighter);
    text-align: right;
    color: var(--el-text-color-primary);
    font-weight: 500;
}

.error-text {
    color: var(--el-color-danger);
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}
</style>